package com.ys.tdm.controller.doc;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.ys.tdm.bean.doc.Doc;
import com.ys.tdm.bean.item.Item;
import com.ys.tdm.bean.module.Module;
import com.ys.tdm.bean.user.User;
import com.ys.tdm.controller.BaseController;
import com.ys.tdm.service.doc.IDocService;
import com.ys.tdm.service.item.IItemService;
import com.ys.tdm.service.module.IModuleService;
import com.ys.tdm.service.user.IUserService;
import com.ys.tdm.util.JsonUtils;
import com.ys.tdm.util.ReturnVo;
import com.ys.tdm.util.SimpleReturnVo;
import com.ys.tdm.util.UUIDGenerator;
import com.ys.tdm.util.UploadImageReturnVo;
/**
 * 
* @Title:  
* @Description:TODO
* @author Troy  
* @date 2018年1月19日 下午3:59:35 
* @version V1.0 
* @Copyright:Copyright (c) 亚厦股份2016 ~ 2017 版权所有
 */
@Controller
@RequestMapping("/doc")
public class DocController extends BaseController{
	private static Logger logger = Logger.getLogger(DocController.class);

	@Resource 
	private IDocService docService;
	@Resource 
	private IItemService itemService;
	@Resource 
	private IUserService userService;
	@Resource 
	private IModuleService moduleService;
	
	@RequestMapping("/gramar")
	public String addUI(ModelMap model,String id, String sessionId) {
		if (StringUtils.isNotBlank(id)) {
			try {
				Doc docById = docService.getDocById(id);
				if (StringUtils.isNotBlank(docById.getContent())) {
					model.addAttribute("docById", docById);
				}
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		return "doc_gramar";
	}
	
	// 文档查询
	@ResponseBody
	@RequestMapping("/docAjax")
	public String docAjax(Item items, Module module) {
		ReturnVo<List<Doc>> vo = new ReturnVo<List<Doc>>(ERROR,"查询失败");
		List<Doc> docs = new ArrayList<Doc>();
		if (StringUtils.isNotBlank(items.getId())) {
			Doc doc = new Doc();
			doc.setItemId(items.getId());
			try {
				docs = docService.getAll(doc);
				for (Doc docInfor : docs) {
					docInfor.setCreateTimestr(new SimpleDateFormat("yy/MM/dd").format(docInfor.getCreateTime()));
				}
				vo.setCode(SUCCESS);
				vo.setData(docs);
				vo.setMsg("查询成功");
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		return JsonUtils.toJson(vo);
		
	}
	
	
	
	
	
	
	// 文档详情
	@RequestMapping("/docDetail")
	public String docDetail(ModelMap modelMap, String id,String formType,HttpServletRequest request, Module module) {
		List<Doc> docs = new ArrayList<Doc>();
		Doc docInfor = new Doc();
		User loginUser = this.getLoginUser(request);
		Cookie[] cookies = request.getCookies();// 这样便可以获取一个cookie数组
		User user = new User();
		if (StringUtils.isNotBlank(formType)) {
			modelMap.addAttribute("formType",formType);
		}
		modelMap.addAttribute("userName", user.getName());
		if (StringUtils.isNotBlank(id)) {
			try {
				docs = docService.getDocByIds(id);
				if (!docs.isEmpty()) {
					docInfor = docs.get(0);
					docInfor.setCreateTimestr(new SimpleDateFormat("yy/MM/dd").format(docInfor.getCreateTime()));
					modelMap.addAttribute("docInfor", docInfor);
				}
				if (null != loginUser && StringUtils.isNotBlank(loginUser.getName())) {
					user.setName(loginUser.getName());
				}
				
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		return "main_meditor";

	}
	
	// 文档删除
	@ResponseBody
	@RequestMapping("/del")
	public String del(String ids, HttpServletRequest request) {
		SimpleReturnVo returnVo = new SimpleReturnVo(ERROR, "删除失败");
		try {
			if (StringUtils.isNotBlank(ids)) {
				docService.delDocByIds(ids);
				itemService.delItemByIds(ids);
				returnVo = new SimpleReturnVo(SUCCESS, "删除成功");
			}
		} catch (Exception e) {
			logger.error("ItemController-del:", e);
			e.printStackTrace();
		}
		return JsonUtils.toJson(returnVo);
	}

	// 添加文档
	@ResponseBody
	@RequestMapping("/add")
	public String add(Doc doc, HttpServletRequest request) {
		SimpleReturnVo returnVo = new SimpleReturnVo(ERROR, "操作失败");
		String uuid = UUIDGenerator.generate();
		User loginUser = this.getLoginUser(request);
		try {
			if (null != loginUser && StringUtils.isNotBlank(loginUser.getName())) {
				if (StringUtils.isNotBlank(doc.getId())) {
					//修改
					doc.setItemId(null);
					doc.setUpdator(loginUser.getName());
					docService.updateDoc(doc);
					returnVo.setResponseMsg("修改成功");
					returnVo.setResponseCode(SUCCESS);
				}else{
					//添加
					doc.setCreator(loginUser.getName());
					doc.setId(uuid);
					docService.insertDoc(doc);
					returnVo.setResponseMsg(uuid);
					returnVo.setResponseCode(2);
				}
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return JsonUtils.toJson(returnVo);
	}
	
	
	// 图片上传
	@ResponseBody
	@RequestMapping("/uploadImages")
	public String uploadImages(@RequestParam(value = "editormd-image-file", required = true) MultipartFile file,
			HttpServletRequest request) {
		UploadImageReturnVo vo = new UploadImageReturnVo(ERROR,"上传失败");
		String realPath = request.getSession().getServletContext().getRealPath("/upload/");  
		String trueFileName = file.getOriginalFilename();
		String suffix = trueFileName.substring(trueFileName.lastIndexOf("."));
		/*String path = request.getContextPath();
		String basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort()
				+ path+"/upload/";*/
		String fileName = UUIDGenerator.generate() + suffix;
			try {
				File targetFile = new File(realPath, fileName);
				if (!targetFile.exists()) {
					targetFile.mkdirs();
				}
				file.transferTo(targetFile);
				vo.setMessage("上传成功");
				vo.setSuccess(SUCCESS);
				vo.setUrl("upload/"+fileName);
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		return JsonUtils.toJson(vo);
	}

}
